package com.tanhua.dubbo.api;

import com.tanhua.dubbo.mongo.VideoApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    //上传视频
    @Override
    public void save(Video video) {
        video.setId(new ObjectId());
        video.setVid(idWorker.getNextId("video"));
        mongoTemplate.save(video);
    }

    //查询视频列表
    @Override
    public PageResult pageResult(Integer page, Integer pagesize) {
        //查询总数
        long count = mongoTemplate.count(new Query(Criteria.where("seeType").is(1)), Video.class);
        //分页查询
        Query query = new Query().limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);


        return new PageResult(page, pagesize, Math.toIntExact(count), list);
    }

    //关注用户
    @Override
    public void saveFollowUser(FocusUser focusUser) {
        focusUser.setId(new ObjectId());
        mongoTemplate.save(focusUser);
    }

    //删除关注用户
    @Override
    public void deleteFollowUser(Long userId, Long followUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
        mongoTemplate.remove(query, Video.class);
    }

    /**
     * 查询指定用户发布的视频
     *
     * @param uid
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long uid, Integer page, Integer pagesize) {
        //查询总数
        long count = mongoTemplate.count(new Query(Criteria.where("userId").is(uid)), Video.class);
        //分页查询
        Query query = new Query(Criteria.where("userId").is(uid)).limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);

        return new PageResult(page, pagesize, Math.toIntExact(count), list);
    }

    /**
     * 获取桃花传音
     *
     * @return
     */



}